<template>
  <div class="order-container">
    <!-- 页面标题 -->
    <div class="page-title">我的订单</div>

    <!-- 状态筛选标签 -->
    <div class="status-filter">
      <el-tag
        :class="{ active: orderStatus === null }"
        @click="handleStatusChange(null)"
      >
        全部订单
      </el-tag>
      <el-tag
        :class="{ active: orderStatus === 0 }"
        type="warning"
        @click="handleStatusChange(0)"
      >
        待支付定金
      </el-tag>
      <el-tag
        :class="{ active: orderStatus === 1 }"
        type="info"
        @click="handleStatusChange(1)"
      >
        已支付定金
      </el-tag>
      <el-tag
        :class="{ active: orderStatus === 2 }"
        type="warning"
        @click="handleStatusChange(2)"
      >
        待支付尾款
      </el-tag>
      <el-tag
        :class="{ active: orderStatus === 3 }"
        type="success"
        @click="handleStatusChange(3)"
      >
        已支付尾款
      </el-tag>
      <el-tag
        :class="{ active: orderStatus === 4 }"
        type="primary"
        @click="handleStatusChange(4)"
      >
        已发货
      </el-tag>
      <el-tag
        :class="{ active: orderStatus === 5 }"
        type="primary"
        @click="handleStatusChange(5)"
      >
        已收货
      </el-tag>
      <el-tag
        :class="{ active: orderStatus === 6 }"
        type="success"
        @click="handleStatusChange(6)"
      >
        已完成
      </el-tag>
      <el-tag
        :class="{ active: orderStatus === 7 }"
        type="danger"
        @click="handleStatusChange(7)"
      >
        已取消
      </el-tag>
    </div>

    <!-- 时间筛选：替换为美观的时间选择器 -->
    <div class="time-filter-container">
      <!-- 时间选择器卡片 -->
      <div class="time-picker-card">
        <!-- 实时时间显示 -->
        <div class="current-time-display">
          <div class="current-time">{{ formattedTime }}</div>
          <div class="current-date">{{ currentDate }}</div>
        </div>

        <!-- 时间选择器主体 -->
        <div class="picker-content">
          <!-- 快捷选项 -->
          <div class="quick-options">
            <button
              v-for="option in quickTimeOptions"
              :key="option.key"
              :class="['quick-btn', { active: activeQuickKey === option.key }]"
              @click="handleQuickTimeSelect(option.key)"
            >
              {{ option.label }}
            </button>
            <button class="quick-btn reset-btn" @click="clearTimeFilter">
              <i class="fas fa-undo"></i> 清空
            </button>
          </div>

          <!-- 日期时间范围选择 -->
          <div class="range-picker">
            <div class="picker-group">
              <label class="picker-label">开始时间</label>
              <input
                type="datetime-local"
                v-model="dateRange.start"
                class="datetime-input"
                @change="handleDateTimeChange"
              />
            </div>
            <span class="range-separator">至</span>
            <div class="picker-group">
              <label class="picker-label">结束时间</label>
              <input
                type="datetime-local"
                v-model="dateRange.end"
                class="datetime-input"
                @change="handleDateTimeChange"
              />
            </div>
          </div>

          <!-- 选择结果展示 -->
          <div class="selection-result">
            <span class="result-label">当前选择：</span>
            <span class="result-value">
              {{ formatSelectedTimeRange }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单列表：指令式 v-loading（无警告） -->
    <div
      class="order-list"
      v-loading="loading"
      element-loading-text="加载中..."
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <el-card
        v-for="order in filteredOrders"
        :key="order.orderId"
        class="order-item"
      >
        <!-- 订单头部信息 -->
        <div class="order-header">
          <div class="order-id">订单编号: {{ order.orderId }}</div>
          <div class="order-time">
            下单时间: {{ formatDate(order.createTime) }}
          </div>
          <el-tag :type="getStatusType(order.orderStatus)">
            {{ getStatusText(order.orderStatus) }}
          </el-tag>
        </div>

        <!-- 订单内容 -->
        <div class="order-body">
          <!-- 设备信息 -->
          <div class="equipment-info">
            <el-image
              :src="getEquipmentCoverImage(order)"
              class="equipment-img"
              fit="cover"
              fallback-src="https://picsum.photos/seed/default/120/120"
            />
            <div class="equipment-detail">
              <div class="equipment-name">
                {{ order.equipment?.brand }} {{ order.equipment?.model }}
              </div>
              <div class="equipment-id">设备ID: {{ order.equipmentId }}</div>
              <div class="equipment-other">
                <span>年份: {{ order.equipment?.year || "未知" }}</span>
                <span>小时数: {{ order.equipment?.hour || "0" }}h</span>
              </div>
            </div>
          </div>

          <!-- 金额信息 -->
          <div class="order-amounts">
            <div class="amount-item">
              <span class="amount-label">订单总金额</span>
              <span class="amount-value"
                >¥{{ (order.orderAmount || 0).toFixed(2) }}</span
              >
            </div>
            <div class="amount-item">
              <span class="amount-label">定金金额</span>
              <span class="amount-value"
                >¥{{ (order.depositAmount || 0).toFixed(2) }}</span
              >
            </div>
            <div class="amount-item">
              <span class="amount-label">尾款金额</span>
              <span class="amount-value"
                >¥{{ (order.balanceAmount || 0).toFixed(2) }}</span
              >
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="order-actions">
            <el-button
              size="small"
              type="primary"
              @click="handleViewDetail(order)"
            >
              查看设备详情
            </el-button>
            <el-button
              size="small"
              type="info"
              @click="handleViewReport(order)"
              :disabled="!order.equipment?.isDetected"
            >
              查看检测报告
            </el-button>

            <!-- 状态相关操作 -->
            <template v-if="order.orderStatus === 0">
              <el-button
                size="small"
                type="success"
                @click="handlePayDeposit(order)"
              >
                支付定金
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleCancelOrder(order)"
                :loading="operateLoading[order.orderId]"
              >
                取消订单
              </el-button>
            </template>

            <!-- 关键修改：状态为1（已支付定金）或2（待支付尾款）时显示支付尾款按钮 -->
            <template v-if="order.orderStatus === 1 || order.orderStatus === 2">
              <el-button
                size="small"
                type="success"
                @click="handlePayBalance(order)"
              >
                支付尾款
              </el-button>
            </template>

            <template v-if="order.orderStatus === 4">
              <el-button
                size="small"
                type="success"
                @click="handleConfirmReceipt(order)"
                :loading="operateLoading[order.orderId]"
              >
                确认收货
              </el-button>
            </template>

            <template v-if="order.orderStatus === 5">
              <el-button
                size="small"
                type="success"
                @click="handleEvaluate(order)"
                :loading="operateLoading[order.orderId]"
              >
                评价
              </el-button>
            </template>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="filteredOrders.length === 0 && !loading"
      description="暂无相关订单"
    />

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailVisible" title="订单详情" :width="800">
      <OrderDetail :order="currentOrder" />
    </el-dialog>

    <!-- 检测报告对话框：指令式 v-loading -->
    <el-dialog
      v-model="reportVisible"
      title="设备检测报告"
      :width="900"
      :before-close="handleReportClose"
    >
      <div
        class="report-container"
        v-loading="!deteXq && reportVisible"
        element-loading-text="加载检测报告中..."
        element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <div v-if="deteXq">
          <!-- 报告基本信息 -->
          <div class="report-header">
            <div class="report-id">
              <span class="label">报告编号：</span>
              <span class="value">{{ deteXq.reportId || "未知" }}</span>
            </div>
            <div class="equipment-id">
              <span class="label">设备ID：</span>
              <span class="value">{{ deteXq.equipmentId || "未知" }}</span>
            </div>
            <div class="businessman-id">
              <span class="label">商家ID：</span>
              <span class="value">{{ deteXq.businessmanId || "未知" }}</span>
            </div>
            <div class="detection-time">
              <span class="label">检测时间：</span>
              <span class="value">{{ formatDate(deteXq.detectionTime) }}</span>
            </div>
            <div class="audit-status">
              <span class="label">审核状态：</span>
              <span class="value">
                <el-tag :type="getAuditStatusType(deteXq.auditStatus)">
                  {{ getAuditStatusText(deteXq.auditStatus) }}
                </el-tag>
              </span>
            </div>
          </div>

          <!-- 检测结果详情 -->
          <div class="report-details">
            <div class="detail-item">
              <span class="label">外观检测：</span>
              <span class="value">{{
                deteXq.appearanceDetection || "无数据"
              }}</span>
            </div>
            <div class="detail-item">
              <span class="label">部件功能检测：</span>
              <span class="value">{{
                deteXq.componentFunctionDetection || "无数据"
              }}</span>
            </div>
            <div class="detail-item">
              <span class="label">性能参数检测：</span>
              <span class="value">{{
                deteXq.performanceParameterDetection || "无数据"
              }}</span>
            </div>
            <div class="detail-item">
              <span class="label">检测结论：</span>
              <span class="value conclusion">{{
                deteXq.detectionConclusion || "无数据"
              }}</span>
            </div>
            <div class="detail-item" v-if="deteXq.auditRemark">
              <span class="label">审核备注：</span>
              <span class="value">{{ deteXq.auditRemark }}</span>
            </div>
            <div class="detail-item">
              <span class="label">审核时间：</span>
              <span class="value">{{
                formatDate(deteXq.auditTime || deteXq.detectionTime)
              }}</span>
            </div>
          </div>

          <!-- 检测报告图片 -->
          <div
            class="report-images"
            v-if="
              deteXq.detectionReportImages &&
              deteXq.detectionReportImages.length
            "
          >
            <h3 class="images-title">检测报告图片</h3>
            <div class="images-container">
              <div
                class="image-item"
                v-for="(image, index) in deteXq.detectionReportImages"
                :key="image.imageId || index"
              >
                <el-image
                  :src="image.imageUrl"
                  :preview-src-list="getImageUrls()"
                  :initial-index="index"
                  class="report-image"
                  fit="cover"
                  :alt="image.imageDesc || `检测图片 ${index + 1}`"
                  fallback-src="https://picsum.photos/seed/report/200/150"
                />
                <div class="image-desc">
                  {{ image.imageDesc || `图片 ${index + 1}` }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, onUnmounted } from "vue";
import axios from "axios";
import { useCounterStore } from "@/stores/counter";
import router from "@/router";
// 导入所有用到的 Element Plus 组件（包括 v-loading 依赖）
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElImage,
  ElButton,
  ElDialog,
  ElEmpty,
  ElLoading,
} from "element-plus";
// 导入 Element Plus 样式（确保组件正常渲染）
import "element-plus/dist/index.css";
import OrderDetail from "./OrderDetail.vue";

// 状态管理
const userStore = useCounterStore();
const orders = ref([]);
const orderStatus = ref(null);
const loading = ref(false); // 订单列表加载状态
const detailVisible = ref(false);
const currentOrder = ref(null);
const deteXq = ref(null); // 检测报告数据
const reportVisible = ref(false); // 检测报告对话框显示状态
const operateLoading = ref({}); // 操作按钮加载状态（按订单ID存储）

// 时间选择器相关
const dateRange = ref({ start: "", end: "" });
let requestStartTime = ""; // 传给后端的开始时间（yyyy-MM-dd HH:mm:ss）
let requestEndTime = ""; // 传给后端的结束时间（yyyy-MM-dd HH:mm:ss）

// 实时时间显示
const currentTime = ref(new Date());
let timer = null;

// 快捷时间选项
const quickTimeOptions = [
  { key: "today", label: "今天" },
  { key: "7days", label: "近7天" },
  { key: "30days", label: "近30天" },
  { key: "1month", label: "近1个月" },
  { key: "3months", label: "近3个月" },
  { key: "6months", label: "近6个月" },
  { key: "month", label: "本月" },
];
const activeQuickKey = ref("");

// 更新实时时间
const updateTime = () => {
  currentTime.value = new Date();
};

// 格式化实时时间显示
const formattedTime = computed(() => {
  return currentTime.value.toLocaleTimeString("zh-CN", {
    hour12: false,
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
});

const currentDate = computed(() => {
  return currentTime.value.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    weekday: "long",
  });
});

// 格式化选择的时间范围显示
const formatSelectedTimeRange = computed(() => {
  if (!dateRange.value.start && !dateRange.value.end) {
    return "未选择时间范围";
  } else if (dateRange.value.start && !dateRange.value.end) {
    return `从 ${formatDateTime(dateRange.value.start)} 开始`;
  } else if (!dateRange.value.start && dateRange.value.end) {
    return `到 ${formatDateTime(dateRange.value.end)} 结束`;
  } else {
    return `${formatDateTime(dateRange.value.start)} 至 ${formatDateTime(
      dateRange.value.end
    )}`;
  }
});

/**
 * 处理日期时间选择变化（确保触发请求）
 */
const handleDateTimeChange = () => {
  // 转换为后端需要的格式（yyyy-MM-dd HH:mm:ss）
  requestStartTime = dateRange.value.start
    ? formatToApiFormat(dateRange.value.start)
    : "";
  requestEndTime = dateRange.value.end
    ? formatToApiFormat(dateRange.value.end)
    : "";

  activeQuickKey.value = ""; // 清除快捷选项激活状态
  console.log("时间筛选参数：", { requestStartTime, requestEndTime }); // 调试用
  selectOrderByUID(); // 强制触发后端请求
};

/**
 * 处理快捷时间选择
 */
const handleQuickTimeSelect = (key) => {
  const now = new Date();
  const end = new Date(now);
  end.setHours(23, 59, 59, 999);
  const start = new Date(now);

  switch (key) {
    case "today":
      start.setHours(0, 0, 0, 0);
      break;
    case "7days":
      start.setTime(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      start.setHours(0, 0, 0, 0);
      break;
    case "30days":
      start.setTime(now.getTime() - 30 * 24 * 60 * 60 * 1000);
      start.setHours(0, 0, 0, 0);
      break;
    case "1month":
      start.setMonth(now.getMonth() - 1);
      start.setHours(0, 0, 0, 0);
      break;
    case "3months":
      start.setMonth(now.getMonth() - 3);
      start.setHours(0, 0, 0, 0);
      break;
    case "6months":
      start.setMonth(now.getMonth() - 6);
      start.setHours(0, 0, 0, 0);
      break;
    case "month":
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      break;
  }

  // 设置日期范围（适配 datetime-local 格式）
  dateRange.value = {
    start: start.toISOString().slice(0, 16),
    end: end.toISOString().slice(0, 16),
  };

  // 更新请求参数
  requestStartTime = formatToApiFormat(dateRange.value.start);
  requestEndTime = formatToApiFormat(dateRange.value.end);

  activeQuickKey.value = key;
  ElMessage.success(
    `已选择「${quickTimeOptions.find((item) => item.key === key).label}」`
  );
  console.log("快捷时间筛选参数：", { requestStartTime, requestEndTime }); // 调试用
  selectOrderByUID(); // 触发后端请求
};

/**
 * 清空时间筛选
 */
const clearTimeFilter = () => {
  dateRange.value = { start: "", end: "" };
  requestStartTime = "";
  requestEndTime = "";
  activeQuickKey.value = "";
  ElMessage.info("已清空时间筛选");
  selectOrderByUID(); // 触发后端请求
};

/**
 * Date对象转API格式字符串（yyyy-MM-dd HH:mm:ss）
 */
const formatToApiFormat = (datetimeLocalValue) => {
  if (!datetimeLocalValue) return "";
  // datetime-local 值格式为 "yyyy-MM-ddTHH:mm"，转换为 "yyyy-MM-dd HH:mm:ss"
  return datetimeLocalValue.replace("T", " ") + ":00";
};

/**
 * 格式化日期时间显示
 */
const formatDateTime = (datetimeLocalValue) => {
  if (!datetimeLocalValue) return "";
  const date = new Date(datetimeLocalValue.replace("T", " "));
  if (isNaN(date.getTime())) return "";
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

/**
 * 获取订单数据（确保参数正确传递给后端）
 */
async function selectOrderByUID() {
  try {
    loading.value = true;
    const params = {
      userId: userStore.userId,
      orderStatus: orderStatus.value === null ? undefined : orderStatus.value,
    };

    // 支持只传开始时间、只传结束时间、或都传
    if (requestStartTime) params.startTime = requestStartTime;
    if (requestEndTime) params.endTime = requestEndTime;

    console.log("请求后端参数：", params); // 调试用：查看最终传给后端的参数
    const res = await axios.post("/eduservice/order/selectOrderByUId", params);

    if (res.data?.code === 20000) {
      orders.value = res.data.data.list || [];
      if (orders.value.length === 0) {
        ElMessage.info("当前筛选条件下无匹配订单");
      }
    } else {
      ElMessage.error("获取订单失败：" + (res.data?.msg || "未知错误"));
      orders.value = [];
    }
  } catch (error) {
    console.error("请求异常:", error);
    ElMessage.error("网络异常，请稍后重试");
    orders.value = [];
  } finally {
    loading.value = false;
  }
}

/**
 * 状态筛选变化
 */
const handleStatusChange = (status) => {
  orderStatus.value = status;
  selectOrderByUID(); // 触发后端请求
};

/**
 * 前端筛选订单（兼容时间筛选逻辑）
 */
const filteredOrders = computed(() => {
  // 无时间筛选：返回所有订单
  if (!requestStartTime && !requestEndTime) return orders.value;

  const startTs = requestStartTime
    ? new Date(requestStartTime).getTime()
    : null;
  const endTs = requestEndTime ? new Date(requestEndTime).getTime() : null;

  // 时间格式异常：返回所有订单
  if ((startTs && isNaN(startTs)) || (endTs && isNaN(endTs)))
    return orders.value;

  return orders.value.filter((order) => {
    const orderTs = new Date(order.createTime).getTime();
    if (isNaN(orderTs)) return false;

    // 只筛选开始时间：订单时间 >= 开始时间
    if (startTs && !endTs) return orderTs >= startTs;
    // 只筛选结束时间：订单时间 <= 结束时间
    if (!startTs && endTs) return orderTs <= endTs;
    // 都筛选：订单时间在两者之间
    return orderTs >= startTs && orderTs <= endTs;
  });
});

/**
 * 获取设备封面图
 */
const getEquipmentCoverImage = (order) => {
  if (!order.equipment) return "https://picsum.photos/seed/default/120/120";
  if (
    order.equipment.equipmentImages &&
    order.equipment.equipmentImages.length > 0
  ) {
    const coverImage = order.equipment.equipmentImages.find(
      (img) => img.isCover
    );
    return coverImage
      ? coverImage.imageUrl
      : order.equipment.equipmentImages[0].imageUrl;
  }
  return `https://picsum.photos/seed/${
    order.equipmentId || Math.random()
  }/120/120`;
};

/**
 * 查看订单详情
 */
const handleViewDetail = (order) => {
  console.log("查看订单详情:", order);
  console.log("eq", order.equipmentId);
  // 跳转到详情页面
  router.push({
    name: "Shang",
    params: {
      equipmentId: order.equipmentId,
    },
  });
};

/**
 * 查看检测报告
 */
const handleViewReport = async (order) => {
  if (!order.equipment) {
    ElMessage.warning("该订单无关联设备");
    return;
  }
  if (!order.equipment.isDetected) {
    ElMessage.warning("该设备未检测，无检测报告");
    return;
  }

  try {
    reportVisible.value = true;
    deteXq.value = null;
    const res = await axios.get(
      `/eduservice/detectionReport/selectDetectionReportById/${order.equipmentId}`
    );
    deteXq.value = res.data.data.data || {};
  } catch (error) {
    console.error("获取检测报告失败:", error);
    ElMessage.error("获取检测报告失败，请稍后重试");
    reportVisible.value = false;
  }
};

/**
 * 关闭检测报告对话框
 */
const handleReportClose = () => {
  deteXq.value = null;
  reportVisible.value = false;
};

/**
 * 支付定金（沙箱支付）
 */
const handlePayDeposit = (order) => {
  // 校验订单状态（只有待支付定金状态可发起支付）
  if (order.orderStatus !== 0) {
    ElMessage.warning("当前订单状态不支持支付定金");
    return;
  }

  // 校验订单ID
  if (!order.orderId) {
    ElMessage.error("订单ID异常，无法发起支付");
    return;
  }

  ElMessageBox.confirm(
    `确定要支付订单 ${order.orderId} 的定金 ¥${(
      order.depositAmount || 0
    ).toFixed(2)} 吗？`,
    "支付定金确认",
    { confirmButtonText: "确认支付", cancelButtonText: "取消", type: "info" }
  )
    .then(() => {
      try {
        // 定金支付接口：http://localhost:9520/advertisement/alipay/pay?orderId=xxx
        const payUrl = `http://localhost:9520/advertisement/alipay/pay?orderId=${order.orderId}`;
        const payWindow = window.open(payUrl, "_blank");

        // 检查窗口是否被浏览器拦截
        if (!payWindow) {
          ElMessage.error("支付窗口被浏览器拦截，请允许弹出窗口后重试");
          return;
        }

        ElMessage.success("正在跳转到定金支付页面...");

        // 监听支付窗口关闭，刷新订单状态
        const checkWindow = setInterval(() => {
          if (payWindow.closed) {
            clearInterval(checkWindow);
            ElMessage.info("定金支付窗口已关闭，正在刷新订单状态...");
            // 延迟刷新订单列表，确保后端已处理支付结果
            setTimeout(() => {
              selectOrderByUID(); // 重新获取订单数据，更新状态
            }, 1500);
          }
        }, 500);
      } catch (error) {
        console.error("定金支付异常:", error);
        ElMessage.error("发起定金支付失败，请重试");
      }
    })
    .catch(() => {
      ElMessage.info("已取消定金支付");
    });
};

/**
 * 支付尾款（沙箱支付）- 支持状态1和2
 */
const handlePayBalance = (order) => {
  // 校验订单状态（已支付定金或待支付尾款可发起支付）
  if (![1, 2].includes(order.orderStatus)) {
    ElMessage.warning("当前订单状态不支持支付尾款");
    return;
  }

  // 校验订单ID（关键修复：确保订单号为字符串类型）
  if (!order.orderId && order.orderId !== 0) {
    ElMessage.error("订单ID异常，无法发起支付");
    return;
  }
  const orderIdStr = String(order.orderId); // 强制转为字符串

  // 校验尾款金额（前端双重校验，避免无效请求）
  if (!order.balanceAmount || order.balanceAmount <= 0) {
    ElMessage.error("尾款金额异常，请重新下单");
    return;
  }

  // 确认文案
  const confirmText = `确定要支付订单 ${orderIdStr} 的尾款 ¥${(
    order.balanceAmount || 0
  ).toFixed(2)} 吗？`;

  ElMessageBox.confirm(confirmText, "支付尾款确认", {
    confirmButtonText: "确认支付",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(() => {
      try {
        // 关键修复：传递字符串类型的订单号，与后端接收类型一致
        const payUrl = `http://localhost:9520/eduservice/alipay/pay?orderId=${encodeURIComponent(
          orderIdStr
        )}`;
        const payWindow = window.open(payUrl, "_blank");

        if (!payWindow) {
          ElMessage.error("支付窗口被浏览器拦截，请允许弹出窗口后重试");
          return;
        }

        ElMessage.success("正在跳转到尾款支付页面...");

        // 监听支付窗口关闭，刷新订单状态
        const checkWindow = setInterval(() => {
          if (payWindow.closed) {
            clearInterval(checkWindow);
            ElMessage.info("尾款支付窗口已关闭，正在刷新订单状态...");
            setTimeout(() => {
              selectOrderByUID(); // 重新获取订单数据，更新状态
            }, 3000);
          }
        }, 500);
      } catch (error) {
        console.error("尾款支付异常:", error);
        ElMessage.error("发起尾款支付失败，请重试");
      }
    })
    .catch(() => {
      ElMessage.info("已取消尾款支付");
    });
};

/**
 * 统一更新订单状态的方法（避免重复代码）
 * @param {Object} order - 订单对象
 * @param {number} targetStatus - 目标状态
 * @param {string} apiPath - 接口路径（相对于/eduservice/order/）
 * @param {string} successMsg - 成功提示文案
 */
const updateOrderStatus = async (order, targetStatus, apiPath, successMsg) => {
  try {
    // 设置当前订单的操作加载状态
    operateLoading.value[order.orderId] = true;
    console.log(`更新订单${order.orderId}状态为${targetStatus}`, order);
    
    // 调用状态更新接口
    const res = await axios.get(`/eduservice/order/${apiPath}/${order.orderId}/${targetStatus}`);
    
    if (res.data?.code === 20000) {
      ElMessage.success(successMsg);
      // 接口成功后立即刷新订单列表（确保拿到最新数据）
      await selectOrderByUID();
    } else {
      ElMessage.error("订单状态更新失败：" + (res.data?.msg || "未知错误"));
    }
  } catch (error) {
    console.error("更新订单状态异常:", error);
    ElMessage.error("网络异常，状态更新失败，请重试");
  } finally {
    // 无论成功失败，都关闭加载状态
    operateLoading.value[order.orderId] = false;
  }
};

/**
 * 取消订单
 */
const handleCancelOrder = (order) => {
  ElMessageBox.confirm(`确定要取消订单 ${order.orderId} 吗？`, "取消确认", {
    confirmButtonText: "确认取消",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 调用统一状态更新方法：目标状态7（已取消），接口路径updateOrderStatus3
      updateOrderStatus(
        order,
        7,
        "updateOrderStatus3",
        "订单已取消"
      );
    })
    .catch(() => ElMessage.info("已取消操作"));
};

/**
 * 确认收货
 */
const handleConfirmReceipt = (order) => {
  ElMessageBox.confirm(
    `确定已收到订单 ${order.orderId} 的货物吗？`,
    "收货确认",
    { confirmButtonText: "确认收货", cancelButtonText: "取消", type: "info" }
  )
    .then(() => {
      // 调用统一状态更新方法：目标状态5（已收货），接口路径updateOrderStatus
      updateOrderStatus(
        order,
        5,
        "updateOrderStatus",
        "已确认收货"
      );
    })
    .catch(() => ElMessage.info("已取消操作"));
};

/**
 * 评价订单
 */
const handleEvaluate = (order) => {
  ElMessageBox.confirm(
    `确定评价订单 ${order.orderId} 吗？`,
    "评价确认",
    { confirmButtonText: "确认评价", cancelButtonText: "取消", type: "info" }
  )
    .then(() => {
      // 调用统一状态更新方法：目标状态6（已完成），接口路径updateOrderStatus2
      updateOrderStatus(
        order,
        6,
        "updateOrderStatus2",
        "评价成功，订单已完成"
      );
    })
    .catch(() => ElMessage.info("已取消操作"));
};

/**
 * 格式化日期显示（兼容空值）
 */
const formatDate = (dateString) => {
  if (!dateString) return "暂无时间";
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return "无效日期";
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

/**
 * 订单状态文本映射
 */
const getStatusText = (status) => {
  const statusMap = {
    0: "待支付定金",
    1: "已支付定金",
    2: "待支付尾款",
    3: "已支付尾款",
    4: "已发货",
    5: "已收货",
    6: "已完成",
    7: "已取消",
  };
  return statusMap[status] || "未知状态";
};

/**
 * 订单状态标签类型映射
 */
const getStatusType = (status) => {
  const typeMap = {
    0: "warning",
    1: "info",
    2: "warning",
    3: "success",
    4: "primary",
    5: "primary",
    6: "success",
    7: "danger",
  };
  return typeMap[status] || "default";
};

/**
 * 审核状态文本映射
 */
const getAuditStatusText = (status) => {
  const statusMap = {
    0: "未审核",
    1: "已审核",
    2: "审核未通过",
  };
  return statusMap[status] || "未知状态";
};

/**
 * 审核状态标签类型映射
 */
const getAuditStatusType = (status) => {
  const typeMap = {
    0: "warning",
    1: "success",
    2: "danger",
  };
  return typeMap[status] || "default";
};

/**
 * 获取检测报告图片URL列表
 */
const getImageUrls = () => {
  return deteXq.value?.detectionReportImages?.map((img) => img.imageUrl) || [];
};

/**
 * 生命周期钩子
 */
onMounted(() => {
  selectOrderByUID(); // 初始化加载订单
  timer = setInterval(updateTime, 1000); // 启动实时时间更新
});

onUnmounted(() => {
  if (timer) clearInterval(timer); // 清除定时器
});
</script>

<style scoped>
/* 基础样式 */
.order-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.status-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  padding: 10px 0;
}

.status-filter .el-tag {
  cursor: pointer;
}

.status-filter .active {
  background-color: #409eff;
  color: white;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
  min-height: 300px; /* 避免加载时布局抖动 */
}

.order-item {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.order-id,
.order-time {
  color: #606266;
  font-size: 14px;
}

.order-body {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.equipment-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 300px;
  gap: 15px;
}

.equipment-img {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  object-fit: cover;
}

.equipment-detail {
  line-height: 1.8;
}

.equipment-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.equipment-id {
  color: #606266;
  font-size: 14px;
}

.equipment-other {
  display: flex;
  gap: 20px;
  color: #606266;
  font-size: 14px;
}

.order-amounts {
  display: flex;
  gap: 30px;
  flex: 1;
  min-width: 300px;
  justify-content: center;
  align-items: center;
}

.amount-item {
  text-align: center;
}

.amount-label {
  display: block;
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.amount-value {
  color: #f56c6c;
  font-weight: 500;
  font-size: 16px;
}

.order-actions {
  display: flex;
  gap: 10px;
  flex: 1;
  min-width: 200px;
  justify-content: flex-end;
}

/* 检测报告样式 */
.report-container {
  padding: 10px 0;
}

.report-header {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 25px;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.report-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.label {
  font-weight: 500;
  color: #606266;
  min-width: 120px;
  text-align: right;
  padding-top: 4px;
}

.value {
  flex: 1;
  color: #303133;
  line-height: 1.8;
}

.conclusion {
  font-weight: 500;
  color: #27ae60;
}

.report-images {
  margin-top: 20px;
}

.images-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #303133;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.image-item {
  width: 200px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.report-image {
  width: 100%;
  height: 150px;
  cursor: pointer;
  border-radius: 4px;
  object-fit: cover;
}

.image-desc {
  font-size: 14px;
  color: #606266;
  word-break: break-all;
  text-align: center;
}

/* 时间选择器样式 */
.time-filter-container {
  margin-bottom: 25px;
}

.time-picker-card {
  background: white;
  border-radius: 15px;
  padding: 25px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.current-time-display {
  text-align: center;
  padding: 15px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 10px;
  color: white;
  margin-bottom: 20px;
}

.current-time {
  font-size: 1.8rem;
  font-weight: bold;
  margin-bottom: 5px;
}

.current-date {
  font-size: 1rem;
  opacity: 0.9;
}

.picker-content {
  margin-top: 20px;
}

.quick-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.quick-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fa;
  color: #5a6c7d;
  display: flex;
  align-items: center;
  gap: 6px;
}

.quick-btn.active {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.quick-btn:hover:not(.active) {
  background: #e9ecef;
}

.quick-btn.reset-btn {
  margin-left: auto;
  color: #999;
  background: #f1f3f4;
}

.quick-btn.reset-btn:hover {
  color: #666;
  background: #e4e6e8;
}

.range-picker {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.picker-group {
  flex: 1;
  min-width: 200px;
}

.picker-label {
  display: block;
  margin-bottom: 8px;
  color: #5a6c7d;
  font-weight: 500;
  font-size: 0.9rem;
}

.datetime-input {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.datetime-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.range-separator {
  color: #7f8c8d;
  font-weight: 500;
  min-width: 20px;
  text-align: center;
}

.selection-result {
  margin-top: 15px;
  padding: 12px 15px;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 0.95rem;
}

.result-label {
  color: #5a6c7d;
  font-weight: 500;
  margin-right: 8px;
}

.result-value {
  color: #2c3e50;
  font-weight: 600;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .order-actions {
    justify-content: center;
    width: 100%;
  }

  .order-amounts {
    justify-content: flex-start;
  }

  .report-header {
    flex-direction: column;
    gap: 10px;
  }

  .detail-item {
    flex-direction: column;
    gap: 5px;
  }

  .label {
    text-align: left;
    padding-top: 0;
  }

  .image-item {
    width: 100%;
  }

  .report-image {
    height: 200px;
  }

  .range-picker {
    flex-direction: column;
    gap: 10px;
  }

  .picker-group {
    width: 100%;
    min-width: auto;
  }

  .quick-btn.reset-btn {
    margin-left: 0;
    width: 100%;
    justify-content: center;
  }
}
</style>